{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "from torch.autograd import Variable\n",
    "\n",
    "dtype = torch.FloatTensor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch:0 loss:3.273170\n",
      "epoch:100 loss:2.161475\n",
      "epoch:200 loss:1.446672\n",
      "epoch:300 loss:1.048739\n",
      "epoch:400 loss:0.818006\n",
      "epoch:500 loss:0.660088\n",
      "epoch:600 loss:0.539275\n",
      "epoch:700 loss:0.439288\n",
      "epoch:800 loss:0.352862\n",
      "epoch:900 loss:0.279044\n",
      "epoch:1000 loss:0.218977\n",
      "epoch:1100 loss:0.172366\n",
      "epoch:1200 loss:0.137162\n",
      "epoch:1300 loss:0.110754\n",
      "epoch:1400 loss:0.090818\n",
      "epoch:1500 loss:0.075571\n",
      "epoch:1600 loss:0.063727\n",
      "epoch:1700 loss:0.054377\n",
      "epoch:1800 loss:0.046883\n",
      "epoch:1900 loss:0.040791\n",
      "epoch:2000 loss:0.035773\n",
      "epoch:2100 loss:0.031592\n",
      "epoch:2200 loss:0.028071\n",
      "epoch:2300 loss:0.025078\n",
      "epoch:2400 loss:0.022512\n",
      "epoch:2500 loss:0.020296\n",
      "epoch:2600 loss:0.018367\n",
      "epoch:2700 loss:0.016680\n",
      "epoch:2800 loss:0.015194\n",
      "epoch:2900 loss:0.013880\n",
      "epoch:3000 loss:0.012712\n",
      "epoch:3100 loss:0.011669\n",
      "epoch:3200 loss:0.010735\n",
      "epoch:3300 loss:0.009894\n",
      "epoch:3400 loss:0.009136\n",
      "epoch:3500 loss:0.008450\n",
      "epoch:3600 loss:0.007827\n",
      "epoch:3700 loss:0.007260\n",
      "epoch:3800 loss:0.006744\n",
      "epoch:3900 loss:0.006271\n",
      "epoch:4000 loss:0.005838\n",
      "epoch:4100 loss:0.005441\n",
      "epoch:4200 loss:0.005076\n",
      "epoch:4300 loss:0.004739\n",
      "epoch:4400 loss:0.004429\n",
      "epoch:4500 loss:0.004142\n",
      "epoch:4600 loss:0.003877\n",
      "epoch:4700 loss:0.003631\n",
      "epoch:4800 loss:0.003404\n",
      "epoch:4900 loss:0.003192\n",
      "[['i', 'like'], ['i', 'love'], ['i', 'hate']] -> ['dog', 'coffee', 'milk']\n"
     ]
    }
   ],
   "source": [
    "sentences = [\"i like dog\", \"i love coffee\", \"i hate milk\"]\n",
    "words = ' '.join(sentences).split(' ')\n",
    "words_dict = list(set(words))\n",
    "num2word = {index:word for index,word in enumerate(words_dict)}\n",
    "word2num = {word:index for index,word in enumerate(words_dict)}\n",
    "\n",
    "n_class = len(words_dict)\n",
    "n_step = 2\n",
    "n_hidden = 2\n",
    "embedding_size = 2\n",
    "\n",
    "def make_batch(sentences):\n",
    "    input_batch = []\n",
    "    target_batch = []\n",
    "    for sen in sentences:\n",
    "        word = sen.split()\n",
    "        input = [word2num[w] for w in word[:-1]]\n",
    "        target = word2num[word[-1]]\n",
    "        \n",
    "        input_batch.append(input)\n",
    "        target_batch.append(target)\n",
    "        \n",
    "    return input_batch,target_batch\n",
    "\n",
    "class NNLM(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(NNLM,self).__init__()\n",
    "        self.C = nn.Embedding(n_class,embedding_size)\n",
    "        self.H = nn.Parameter(torch.randn(n_step*embedding_size,n_hidden).type(dtype))\n",
    "        self.W = nn.Parameter(torch.randn(n_step*embedding_size,n_class).type(dtype))\n",
    "        self.d = nn.Parameter(torch.randn(n_hidden).type(dtype))\n",
    "        self.U = nn.Parameter(torch.randn(n_hidden,n_class).type(dtype))\n",
    "        self.b = nn.Parameter(torch.randn(n_class).type(dtype))\n",
    "        \n",
    "    def forward(self,X):\n",
    "        X = self.C(X)\n",
    "        X = X.view(-1,n_step*embedding_size)\n",
    "        tanh = torch.tanh(torch.mm(X,self.H)+self.d)\n",
    "        return torch.mm(tanh,self.U)+torch.mm(X,self.W)+self.b\n",
    "    \n",
    "model = NNLM()\n",
    "criterion = nn.CrossEntropyLoss()\n",
    "optimizer = optim.Adam(model.parameters(),lr=0.001)\n",
    "\n",
    "input_batch,target_batch = make_batch(sentences)\n",
    "input_batch = Variable(torch.LongTensor(input_batch))\n",
    "target_batch = Variable(torch.LongTensor(target_batch))\n",
    "\n",
    "for epoch in range(5000):\n",
    "    \n",
    "    optimizer.zero_grad()\n",
    "    predict = model(input_batch)\n",
    "    loss = criterion(predict,target_batch)\n",
    "    if epoch%100 == 0:\n",
    "        print('epoch:%d loss:%f' % (epoch,loss))\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "    \n",
    "prediction = model(input_batch).data.max(1,keepdim=True)[1]\n",
    "# Test\n",
    "print([sen.split()[:2] for sen in sentences], '->', [num2word[n.item()] for n in prediction.squeeze()])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
